package com.aijle.videopaper.util;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Build;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;

public class WindowWidgetManager implements IWidgetManager {
    WindowManager mWindowManager;
    private WindowManager.LayoutParams mParams;

    public WindowWidgetManager(Context context) {
        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        // 创建布局参数
        mParams = new WindowManager.LayoutParams();
        // 设置类型
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Android O 以上，使用TYPE_APPLICATION_OVERLAY弹窗类型
            mParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            // Android O 以下，使用TYPE_SYSTEM_ALERT弹窗类型
            mParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
        }
        // 设置标签（FLAG_NOT_FOCUSABLE表示窗口不会获取焦点；FLAG_NOT_TOUCHABLE表示窗口不会接收Touch事件，即将Touch事件向下层分发）
        mParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE |
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR |
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
        // 设置位图模式 （PixelFormat.RGBA_8888可以使背景透明。不设置默认PixelFormat.OPAQUE，即不透明）
        mParams.format = PixelFormat.TRANSLUCENT;
        // 设置分布位置（距左对齐 + 距顶对齐）
        mParams.gravity = Gravity.LEFT | Gravity.TOP;
//            mParams.dimAmount = 0;
        // 设置布局宽/高为自适应
        mParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        mParams.height = WindowManager.LayoutParams.MATCH_PARENT;
    }
    
    @Override
    public void addView(View view) {
        mWindowManager.addView(view, mParams);
    }

    @Override
    public void removeView(View view) {
        mWindowManager.removeView(view);
    }

    @Override
    public void updateLayout(View view, float alpha) {
        mParams.alpha = alpha;
        if (view.getParent() == null) {
            mWindowManager.addView(view, mParams);
        } else {
            mWindowManager.updateViewLayout(view, mParams);
        }
    }
}
